<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑任务' : '创建任务'"
    width="60%"
    @close="handleClose">
    
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择任务状态" style="width: 100%">
              <el-option label="未开始" value="not_started" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已延迟" value="delayed" />
              <el-option label="已阻塞" value="blocked" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="任务描述" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="3"
          placeholder="请输入任务描述" />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="start_date">
            <el-date-picker 
              v-model="form.start_date" 
              type="date" 
              placeholder="选择开始日期" 
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="due_date">
            <el-date-picker 
              v-model="form.due_date" 
              type="date" 
              placeholder="选择截止日期" 
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预估工时" prop="estimated_hours">
            <el-input-number 
              v-model="form.estimated_hours" 
              :min="0" 
              :precision="1"
              placeholder="小时"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际工时" prop="actual_hours">
            <el-input-number 
              v-model="form.actual_hours" 
              :min="0" 
              :precision="1"
              placeholder="小时"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属阶段" prop="phase_id">
            <el-select v-model="form.phase_id" placeholder="请选择阶段" style="width: 100%">
              <el-option 
                v-for="phase in phases" 
                :key="phase.id" 
                :label="phase.name" 
                :value="phase.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="assignee_id">
            <el-select v-model="form.assignee_id" placeholder="请选择负责人" style="width: 100%">
              <el-option 
                v-for="user in users" 
                :key="user.id" 
                :label="user.full_name || user.username" 
                :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="任务进度" prop="progress">
        <el-slider 
          v-model="form.progress" 
          :step="5" 
          show-stops 
          show-input
          :format-tooltip="(val) => val + '%'" />
      </el-form-item>
      
      <el-form-item label="父任务" prop="parent_id">
        <el-select v-model="form.parent_id" placeholder="请选择父任务（可选）" style="width: 100%">
          <el-option label="无父任务" :value="null" />
          <el-option 
            v-for="task in parentTasks" 
            :key="task.id" 
            :label="task.name" 
            :value="task.id" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'TaskDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    projectId: {
      type: Number,
      required: true
    },
    task: {
      type: Object,
      default: null
    },
    phases: {
      type: Array,
      default: () => []
    },
    users: {
      type: Array,
      default: () => []
    },
    parentTasks: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const loading = ref(false)
    
    const form = reactive({
      name: '',
      description: '',
      status: 'not_started',
      priority: 'medium',
      start_date: '',
      due_date: '',
      estimated_hours: null,
      actual_hours: 0,
      progress: 0,
      phase_id: null,
      assignee_id: null,
      parent_id: null
    })
    
    const rules = {
      name: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择任务状态', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      start_date: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ],
      due_date: [
        { required: true, message: '请选择截止日期', trigger: 'change' }
      ]
    }
    
    // 计算属性
    const visible = ref(props.modelValue)
    const isEdit = ref(false)
    
    // 监听props变化
    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal
    })
    
    watch(() => props.task, (newTask) => {
      if (newTask) {
        isEdit.value = true
        Object.assign(form, {
          name: newTask.name,
          description: newTask.description || '',
          status: newTask.status,
          priority: newTask.priority,
          start_date: newTask.start_date,
          due_date: newTask.due_date,
          estimated_hours: newTask.estimated_hours,
          actual_hours: newTask.actual_hours || 0,
          progress: newTask.progress || 0,
          phase_id: newTask.phase_id,
          assignee_id: newTask.assignee_id,
          parent_id: newTask.parent_id
        })
      } else {
        isEdit.value = false
        resetForm()
      }
    })
    
    // 监听visible变化
    watch(visible, (newVal) => {
      emit('update:modelValue', newVal)
    })
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        name: '',
        description: '',
        status: 'not_started',
        priority: 'medium',
        start_date: '',
        due_date: '',
        estimated_hours: null,
        actual_hours: 0,
        progress: 0,
        phase_id: null,
        assignee_id: null,
        parent_id: null
      })
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      resetForm()
    }
    
    // 提交表单
    const handleSubmit = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const formData = {
              ...form,
              project_id: props.projectId
            }
            
            // 这里应该调用API
            console.log('提交任务数据:', formData)
            
            ElMessage.success(isEdit.value ? '更新任务成功' : '创建任务成功')
            emit('success')
            handleClose()
          } catch (error) {
            ElMessage.error(isEdit.value ? '更新任务失败' : '创建任务失败')
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    return {
      formRef,
      form,
      rules,
      loading,
      visible,
      isEdit,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
